<template>
  <c-dialog ref="dialog" :data="selData" single title="整改延期">
    <c-list ref="form" :column="1" :model="formData" :rules="formRules" label-width="160px">
      <c-list-item label="整改任务" :value="detail.taskCode" />
      <c-list-item label="验收任务" :value="detail.acceptTaskCode" />
      <c-list-item label="门店建设项目号" :value="detail.constCode" />
      <c-list-item label="所属门店编码" :value="detail.shopCode" />
      <c-list-item label="所属门店" :value="detail.shopName" />
      <c-list-item label="原预计整改完成时间" :value="detail.expectEndTime" />
      <c-list-item prop="expectEndTime" label="变更后预计整改完成时间">
        <el-date-picker
          v-model="formData.expectEndTime"
          type="date"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="选择日期"
        />
      </c-list-item>
      <c-list-item v-if="detail.rectifyType==='HARD'" label="延期原因" prop="delayReason">
        <el-input v-model="formData.delayReason" type="textarea" maxlength="1024" show-word-limit style="width:100%" :autosize="{minRows:3}" placeholder="延期原因" clearable />
      </c-list-item>
      <c-section v-if="detail.rectifyType==='SOFT'" title="整改异常清单">
        <c-table-box
          checkbox
          hide-func
          :table-height="400"
          :data="softTableData"
          :table-row-key="tableRowKey"
          :table-config="softTableConfig"
          @selection-change="selectionChangeHandle"
        >
          <template #btn>
            <c-button type="primary" @click="addTableRow">新增</c-button>
            <c-button type="primary" @click="removeTableRow">删除</c-button>
            <!-- <el-upload
              style="margin:0 10px"
              :action="action"
              :headers="headers"
              :multiple="false"
              name="file"
              :show-file-list="false"
              accept=".xlsx"
              :on-success="importHandle"
            >
              <c-button type="primary">导入</c-button>
            </el-upload>
            <c-button type="primary" @click="downTemplate">下载导入模板</c-button> -->
          </template>
        </c-table-box>
      </c-section>
      <!-- 新增整改延期明细：问题类型、缺货类别、整改异常问题描述、建议解决方案、备注字段； -->
      <c-list-item>
        <div class="btn-container">
          <c-button @click="clickCancelHandle">取消</c-button>
          <c-button type="primary" @click="clickConfirmHandle">确认</c-button>
        </div>
      </c-list-item>
    </c-list>
  </c-dialog>
</template>
<script>
import { postDelay, importTemplate } from '@/api/rectify'
import { fileDown } from '@/utils'
import { getToken } from '@/utils/auth'

export default {
  name: 'Postpone',
  props: {
    selData: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      softTableConfig: {
        interfacePath: '',
        setting: [
          {
            prop: 'problemCategory',
            label: '问题类型',
            render: (h, row) => {
              return h('c-remote-select', {
                props: {
                  url: '/api/v1/configAcceptProblem/page',
                  method: 'POST',
                  value: row.problemCategory,
                  valueName: 'problemClass',
                  labelName: 'problemClass',
                  filtersRaw: this.softFiltersRaw
                },
                attrs: {
                  placeholder: '请选择问题类型'
                },
                on: {
                  input: v => {
                    this.$set(row, 'problemCategory', v)
                    this.$set(row, 'stockoutType', '')
                  }
                }
              })
            }
          },
          {
            prop: 'stockoutType',
            label: '缺货类别',
            render: (h, row) => {
              return h('c-dict-select', {
                props: {
                  disabled: row.problemCategory !== '产品缺货',
                  dictTypeCode: 'STOCKOUT_TYPE',
                  value: row.stockoutType
                },
                on: {
                  input: v => {
                    this.$set(row, 'stockoutType', v)
                  }
                }
              })
            }
          },
          {
            prop: 'exceptionDesc',
            label: '整改异常问题描述',
            edit: {
              canEdit: true,
              editType: 'text',
              maxlength: 2000
            }
          },
          {
            prop: 'solution',
            label: '建议解决方案',
            edit: {
              canEdit: true,
              editType: 'text',
              maxlength: 2000
            }
          },
          {
            prop: 'remark',
            label: '备注',
            edit: {
              canEdit: true,
              editType: 'text',
              maxlength: 2000
            }
          }
        ]
      },
      softTableData: [],
      formData: {
        expectEndTime: '',
        delayReason: ''
      },
      headers: {
        'X-Token': this.$store.getters.token ? getToken() : '',
        'Authorization': this.$store.getters.token ? 'Bearer ' + getToken() : ''
      },
      formRules: {
        expectEndTime: [{ required: true, message: '请选择变更后预计整改完成时间', trigger: 'change' }],
        delayReason: [{ required: true, message: '请填写延期原因', trigger: 'change' }]
      }
    }
  },
  computed: {
    detail() {
      return this.selData.length > 0 ? this.selData[0] : {}
    },
    action() {
      if (this.detail.rectifyType === 'HARD') {
        return '/slm-admin/api/v1/acceptRectifyTask/hardImportExcel'
      } else {
        return '/slm-admin/api/v1/acceptRectifyTask/softImportExcel'
      }
    },
    softFiltersRaw() {
      const b = this.detail.belongDuty
      const t = [
        { key: 'acceptType', value: 'SOFT', operator: '=' },
        { key: 'enable', value: '1', operator: '=' }
      ]
      if (b) {
        t.push({ key: 'belongDuty', value: b, operator: '=' })
      }
      if (this.problemTypes.length > 0) {
        t.push({ key: 'problemClass', value: `[${this.problemTypes.join(',')}]`, operator: 'in' })
      }
      return t
    },
    problemTypes() {
      const problemList = this.detail.problemList || []
      const t = []
      problemList.forEach(e => {
        const pl = e.problemDetailDTOList || []
        pl.forEach(p => {
          t.push(p.problemType)
        })
      })
      return t
    }
  },
  methods: {
    selectionChangeHandle(v) {
      if (this.detail.rectifyType === 'SOFT') {
        this.softSelections = v
      }
    },
    tableRowKey(row) {
      return row._key
    },
    addTableRow() {
      if (this.detail.rectifyType === 'SOFT') {
        this.softTableData.unshift({
          problemCategory: '',
          stockoutType: '',
          exceptionDesc: '',
          solution: '',
          remark: '',
          belongDuty: this.detail.belongDuty,
          _key: Math.floor(Math.random() * 0xfffff).toString(16)
        })
      }
    },
    removeTableRow() {
      let d = this.tableData; let s = this.selections
      if (this.detail.rectifyType === 'SOFT') {
        d = this.softTableData
        s = this.softSelections
      }
      if (!this.singleJudge(s, '删除', false)) {
        this.$message.warning('请选择数据！')
        return
      }
      const result = d.filter(e => {
        return !s.includes(e)
      })
      if (this.detail.rectifyType === 'SOFT') {
        this.softTableData = result
        this.softSelections = []
      }
    },
    clickConfirmHandle() {
      return this.$refs.form.validate().then(() => {
        return this.$gsec('EXCEPT029').then(([cfg, ecd]) => {
          const d = this.detail
          ecd.constCode = d.constCode
          ecd.bizCode = d.taskCode
          ecd.modelId = d.id
          ecd.bizName = d.rectifyType === 'HARD' ? '硬装整改延期' : '软装整改延期'
          ecd.exceptionDesc = this.formData.delayReason
          const t = this.$gsed()
          t.expectEndTime = this.formData.expectEndTime
          t.exceptionDesc = this.formData.delayReason

          t.beforeAdjustTime = d.expectEndTime || ''
          t.afterAdjustTime = (this.formData.expectEndTime || '').replace(/ \d{2}:\d{2}:\d{2}/, ' 23:59:59')
          // t.belongDuty = d.belongDuty || ''
          t.remark = ''
          ecd.shopExceptionDetailDTOS = this.detail.rectifyType === 'SOFT' ? this.softTableData.map(v => { return { ...t, ...v } }) : [t]
          const data = {
            exceptionDTO: ecd,
            id: d.id
            // ...this.formData
          }
          // return
          return postDelay(data).then(res => {
            this.$message.success('操作成功！')
            this.$emit('on-success')
            this.$refs.dialog.visible = false
          })
        })
      })
    },
    clickCancelHandle() {
      this.$refs.dialog.visible = false
    },
    // 导入
    importHandle(response, file, fileList) {
      // console.log(response, file, fileList)
      if (response.success !== 1) {
        this.$message.error(response.msg)
        return
      }
      if (this.detail.rectifyType === 'SOFT') {
        this.softTableData.unshift(...response.data)
      } else {
        this.tableData.unshift(...response.data)
      }
    },
    // 下载模板
    downTemplate() {
      return importTemplate(this.detail.rectifyType === 'SOFT' ? 'soft' : 'hard').then(res => {
        const t = URL.createObjectURL(res)
        fileDown(t, '整改异常导入模板.xlsx')
      })
    }
  }
}
</script>
